package com.asen.commons.core.jdbc.handler;

import com.asen.commons.core.base.domain.Core;
import com.asen.commons.core.meta.entity.EntityField;
import com.asen.commons.core.utils.EntityUtils;
import com.asen.commons.core.utils.FieldUtils;

import java.sql.*;
import java.util.Collection;
import java.util.List;

/**
 * Date 类型处理器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-02
 */
public class LongTypeHandler extends BaseTypeHandler<Long> {

    @Override
    public int getSqlType() {
        return Types.BIGINT;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long parameter)
            throws SQLException {
        ps.setLong(i, parameter);
    }

    @Override
    public Long getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getLong(columnName);
    }

    @Override
    public Long getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getLong(columnIndex);
    }

    @Override
    public Long getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getLong(columnIndex);
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Long || value instanceof String) {
            return value.toString();
        }

        if (value instanceof String[]) {
            return getSqlValue((String[]) value, false);
        }

        if (value instanceof Long[]) {
            return getSqlValue((Long[]) value);
        }

        if (value instanceof Collection) {
            return getSqlValue((Collection) value, false);
        }

        return String.valueOf(value);
    }

    @Override
    public Long getValue(Object value) throws Exception {
        if (value == null) {
            return null;
        }

        if (Long.class.isAssignableFrom(value.getClass())) {
            return (Long) value;
        }

        if (Number.class.isAssignableFrom(value.getClass())) {
            return ((Number) value).longValue();
        }

        if (EntityUtils.isSimpleType(value.getClass())) {
            String str = value.toString().trim();
            if (str.length() == 0) {
                return null;
            }
            return Long.valueOf(str);
        }

        if (Core.class.isAssignableFrom(value.getClass())) {
            Core actualValue = (Core) value;
            return actualValue.getId();
        }

        List<EntityField> efList = FieldUtils.getFieldList(value.getClass());
        EntityField idEf = null;
        for (EntityField ef : efList) {
            if (ef.getName().equals("id")) {
                idEf = ef;
                break;
            }
        }

        if (idEf != null) {
            return (Long) idEf.getValue(value);
        }

        return null;
    }
}
